package net.techwatch.jpa.dao;

import java.lang.reflect.ParameterizedType;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 * @author Vincent Partington
 * 
 * For more details look at the article <a
 * href="http://blog.xebia.com/2009/03/09/jpa-implementation-patterns-data-access-objects/">JPA
 * implementation patterns: Data access objects</a>
 * 
 * @param <K>
 * @param <E>
 */
public class JpaDao<K, E> implements Dao<K, E> {

	/**
	 * 
	 */
	protected Class<E> entityClass;

	/**
	 * 
	 */
	@PersistenceContext
	private EntityManager entityManager;

	/**
	 * 
	 */
	public JpaDao() {
		ParameterizedType genericSuperclass = (ParameterizedType) getClass()
				.getGenericSuperclass();
		this.entityClass = (Class<E>) genericSuperclass
				.getActualTypeArguments()[1];
	}

	public EntityManager getEntityManager() {
		return entityManager;
	}

	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see net.techwatch.jpa.dao.Dao#persist(java.lang.Object)
	 */
	public void persist(E entity) {
		entityManager.persist(entity);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see net.techwatch.jpa.dao.Dao#remove(java.lang.Object)
	 */
	public void remove(E entity) {
		entityManager.remove(entity);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see net.techwatch.jpa.dao.Dao#findById(java.lang.Object)
	 */
	public E findById(K id) {
		return entityManager.find(entityClass, id);
	}
	
}
